package main

import (
	"fmt"
	"github.com/kolesa-team/go-webp/encoder"
	"github.com/kolesa-team/go-webp/webp"
	"image"
	"image/jpeg"
	"image/png"
	"log"
	"os"
	"strings"
)

type Photo struct {
	FileName  string
	PhotoType string
	SrcPath   string
	Fp        *os.File
}

func (p *Photo) CloseFp() {
	_ = p.Fp.Close()
}

func GetPhotos(inputPath string) (photos []*Photo) {
	//获取目录下的所有文件
	files, _ := os.ReadDir(inputPath)
	photos = make([]*Photo, 0, len(files))
	for _, file := range files {
		//排除目录
		if !file.IsDir() {
			p := &Photo{}
			p.FileName = file.Name()
			p.SrcPath = inputPath + "/" + file.Name()
			f, err := os.Open(p.SrcPath)
			if err != nil {
				log.Println(err)
				continue
			}
			p.Fp = f
			p.PhotoType = file.Name()[strings.LastIndex(file.Name(), ".")+1:]
			photos = append(photos, p)
		}
	}
	return
}

func Image2Webg(photo *Photo, outputPath string) {
	//close filePoint
	defer photo.CloseFp()
	var err error
	var f *os.File
	var img image.Image
	//get img
	switch photo.PhotoType {
	case "jpg", "jpeg":
		img, err = jpeg.Decode(photo.Fp)
	case "png":
		img, err = png.Decode(photo.Fp)
	default:
		err = fmt.Errorf("no match")
	}
	if err != nil {
		log.Println(err)
		return
	}
	//get output filePath
	idx := strings.LastIndex(photo.FileName, ".")
	outputFilePath := outputPath + "/" + photo.FileName[:idx+1] + "webg"
	f, err = os.OpenFile(outputFilePath, os.O_CREATE|os.O_WRONLY, 0777)
	if err != nil {
		log.Println(err)
		return
	}
	//get webg options
	options, err := encoder.NewLossyEncoderOptions(encoder.PresetDefault, 75)
	if err != nil {
		log.Println(err)
		return
	}
	//save
	err = webp.Encode(f, img, options)
	if err != nil {
		log.Println(err)
	}
}

func main() {
	inputPath := "./input"
	outputPath := "./output"
	//create output dir
	_, err := os.Stat(outputPath)
	if os.IsNotExist(err) {
		_ = os.Mkdir(outputPath, 0777)
	}
	photos := GetPhotos(inputPath)
	for _, p := range photos {
		Image2Webg(p, outputPath)
	}
}
